//
//  DiagramDetailViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/1/22.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "DiagramDetailViewController.h"
#import "aMyScrollView.h"
#import "DiagramModel.h"

@interface DiagramDetailViewController ()

@property (nonatomic, strong)UILabel *indexLabel;
@property (nonatomic, strong)UIButton *btnOfSave;
@property (nonatomic, strong)NSMutableArray *arrScroll;

@end

@implementation DiagramDetailViewController

- (NSMutableArray *)arrScroll {
    if (_arrScroll == nil) {
        _arrScroll = [NSMutableArray array];
    }
    return _arrScroll;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UIApplication sharedApplication] setStatusBarHidden:YES];

    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

    [self initScrollView:(int)_index];
    
    if (![WShareUtil strNilOrEmpty:self.strTitle] || ![WShareUtil strNilOrEmpty:self.strImage]) {//传了分享标题、图片，则显示分享按钮
        
        // 右上角分享按钮
        [self loadRightBtn];
    }
}

- (void)loadRightBtn {
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:@"more.png"] forState:UIControlStateNormal];
    btn2.frame = CGRectMake(0, 0, 30, 30);
    [btn2 addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtn2 = [[UIBarButtonItem alloc]initWithCustomView:btn2];
    self.navigationItem.rightBarButtonItem = barBtn2;
}

- (void)initScrollView:(int)index {
    scrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
    scrView.contentSize = CGSizeMake(WSCREENH_WIDTH * [WShareUtil sharedData].arrMdiagram.count, WSCREENH_HEIGHT - 64);
    scrView.showsHorizontalScrollIndicator = NO;
    scrView.pagingEnabled = YES;
    scrView.bounces = NO;
    scrView.userInteractionEnabled = YES;

    [scrView setContentOffset:CGPointMake(WSCREENH_WIDTH * index,0) animated:YES];

    for (int i=0; i<[WShareUtil sharedData].arrMdiagram.count; i++)
    {
        aMyScrollView *ascrView = [[aMyScrollView alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH *i, 0, WSCREENH_WIDTH, scrView.bounds.size.height)];
        ascrView.tag = 100+i;

        [self.arrScroll addObject:ascrView];

        if (i == self.index) {
            //            ascrView.strImgUrl = [self.arrMdiagram[self.index] imgsrc];
            NSString *strContent = [[WShareUtil sharedData].arrMdiagram[self.index] strContent];
            NSArray *array = [strContent componentsSeparatedByString:@"img src=\""];
            strContent = [array[1] componentsSeparatedByString:@"\""][0];
            ascrView.strImgUrl = strContent;

            if ((self.index + 1) % 10 == 0 && self.index == [WShareUtil sharedData].arrMdiagram.count - 1) {

                [WShareUtil sharedData].j = 1 + ((int)self.index + 1)/10;
                NSString *z = [NSString stringWithFormat:@"%d",([WShareUtil sharedData].j)];
                [self requestListDataStrNum:z scroll:self.index isRefresh:NO];
                [WShareUtil sharedData].j ++;

            }
        }
        [scrView addSubview:ascrView];
    }
    scrView.delegate = self;

    [self.view addSubview:scrView];

    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, 44)];
    bgView.backgroundColor = [UIColor grayColor];
    bgView.alpha = 0.5;
    [self.view addSubview:bgView];
    [bgView addSubview:self.indexLabel];

    self.indexLabel.text = [NSString stringWithFormat:@"%zd/%zd",self.index + 1,[[WShareUtil sharedData].arrMdiagram count]];
    [self.indexLabel setTextColor:[UIColor whiteColor]];
    lastPage = 0;

}

#pragma mark -
#pragma mark === UIScrollView Delegate ===
#pragma mark -
//ScrollView 划动的动画结束后调用.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    if (lastPage != page)
    {
        aMyScrollView *aView = (aMyScrollView *)[scrView viewWithTag:100+lastPage];
        aView.zoomScale = 1.0;

        lastPage = page;

        if ((page + 1)%10 == 0 && page == [WShareUtil sharedData].arrMdiagram.count - 1) {

            int c = ceil ([WShareUtil sharedData].arrMdiagram.count/10.) + 1;
            NSString *z = [NSString stringWithFormat:@"%d",c];
            [self requestListDataStrNum:z scroll:(int)page isRefresh:NO];
        }
    }
//    else {
////        int i = ceil ([WShareUtil sharedData].arrMdiagram.count/10.) + 1;
//        NSString *z = [NSString stringWithFormat:@"%d",([WShareUtil sharedData].j + 1)];
//        WLog(@"%@",z);
//        [self requestListDataStrNum:z scroll:(int)page isRefresh:NO];
//
//    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    _index = (int)page;

    if ([self.arrScroll count] > 0 && [[WShareUtil sharedData].arrMdiagram count] > 0) {
        aMyScrollView *scrollView = self.arrScroll[_index];

        WLog(@"%@",[[WShareUtil sharedData].arrMdiagram[self.index] strContent]);
//        scrollView.strImgUrl = [self.arrMdiagram[_index] imgsrc];
        NSString *strContent = [[WShareUtil sharedData].arrMdiagram[self.index] strContent];
        NSArray *array = [strContent componentsSeparatedByString:@"src=\""];
        strContent = [array[1] componentsSeparatedByString:@"\""][0];
        scrollView.strImgUrl = strContent;
    }

//    self.indexLabel.text = [NSString stringWithFormat:@"%zd/%zd",page + 1,[[WShareUtil sharedData].arrMdiagram count]];

}


- (void)viewDidUnload
{
    scrView = nil;
}

- (void)dealloc
{
    //[scrView release];
    //[super dealloc];
}

#pragma mark - 下载列表数据
- (void)requestListDataStrNum:(NSString *)pageNum scroll:(NSInteger)index isRefresh:(BOOL)isRefresh{

    WLog(@"%@",pageNum);
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"xxfb",@"content":@{@"revert":@"paginate",@"colcode":@"57",@"pagesize":@"10",@"pagenumber":pageNum}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([returnDic[@"data"] count] <= 0) {
            [SVProgressHUD showImage:nil status:@"已到最后一页"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
        }
        for (NSDictionary *dic in returnDic[@"data"]) {
            DiagramModel *diagramModel = [DiagramModel mj_objectWithKeyValues:dic];
            [[WShareUtil sharedData].arrMdiagram addObject:diagramModel];
        }

        [scrView removeFromSuperview];
        [self initRequestScrollView:index];
//        scrView.contentSize = CGSizeMake(WSCREENH_WIDTH * [WShareUtil sharedData].arrMdiagram.count, WSCREENH_HEIGHT - 64);
//        for (int i = 0; i < [returnDic[@"data"] count]; i++) {
//
//            WLog(@"%d===",(pageNum.intValue -1)*10 + i + 1);
//
//            aMyScrollView *ascrView = [[aMyScrollView alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH *(pageNum.intValue -1)*10 + i + 1, 0, WSCREENH_WIDTH, scrView.bounds.size.height)];
//            ascrView.tag = 100+ ([pageNum intValue] - 1)*10 + i;
//            [self.arrScroll addObject:ascrView];
//            WLog(@"%ld===",self.arrScroll.count);
//
//            [scrView addSubview:ascrView];
//
//            scrView.delegate = self;
//        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)initRequestScrollView:(NSInteger)index {
    scrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
    scrView.contentSize = CGSizeMake(WSCREENH_WIDTH * [WShareUtil sharedData].arrMdiagram.count, WSCREENH_HEIGHT - 64);
    scrView.showsHorizontalScrollIndicator = NO;
    scrView.pagingEnabled = YES;
    scrView.bounces = NO;
    scrView.userInteractionEnabled = YES;

    [scrView setContentOffset:CGPointMake(WSCREENH_WIDTH * index,0) animated:YES];

    [self.arrScroll removeAllObjects];
    for (int i=0; i<[WShareUtil sharedData].arrMdiagram.count; i++)
    {
        aMyScrollView *ascrView = [[aMyScrollView alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH *i, 0, WSCREENH_WIDTH, scrView.bounds.size.height)];
        ascrView.tag = 100+i;

        [self.arrScroll addObject:ascrView];

        if (i == index) {
            //            ascrView.strImgUrl = [self.arrMdiagram[self.index] imgsrc];
            NSString *strContent = [[WShareUtil sharedData].arrMdiagram[self.index] strContent];
            NSArray *array = [strContent componentsSeparatedByString:@"src=\""];
            strContent = [array[1] componentsSeparatedByString:@"\""][0];
            ascrView.strImgUrl = strContent;
        }
        [scrView addSubview:ascrView];
    }
    scrView.delegate = self;

    [self.view addSubview:scrView];

    lastPage = 0;

}

- (void)rightClick:(UIButton *)btn {

    WLog(@"%@",self.strUrl);
    WLog(@"%@",self.strTitle);
    WLog(@"%@",self.strImage);

    NSString *theLast = [self.strUrl substringFromIndex:[self.strUrl length]-1];
    if (![theLast isEqualToString:@"?"]) {
        self.strUrl = [self.strUrl stringByAppendingString: @"?"];
    }

    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone)]];
    // --- 设置分享面板的UI
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.isShow = YES;//有无标题
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.isShow = YES;//有无取消
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.shareTitleViewTitleString = @"";//标题文字
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.shareCancelControlText = @"取消";//取消文字
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemWidth = 50;//每页Items的最大宽度(白圈的大小)
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemHeight = 90;//每页Items的最大高度(背景的高低)

    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的1确定所选平台进行下一步操作

        /*
         详情
         */
        NSString *descrStr = [WShareUtil filterHTML:nil];
        descrStr = [descrStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];//去掉特殊符号
        descrStr = [descrStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉左右两端的空格
        /*
         图片
         */
        NSURL *imgUrl = [NSURL URLWithString:self.strImage];
        NSData *dateImg = [NSData dataWithContentsOfURL:imgUrl];

        if (dateImg == nil || dateImg.length <= 0) {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:self.strTitle descr:descrStr thumImage:[UIImage imageNamed:@"logo_share.png"]];
            webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",self.strUrl];
            WLog(@"%@",webO.webpageUrl);
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {

                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];

                }
            }];
        } else {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:self.strTitle descr:descrStr thumImage:dateImg];
            webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",self.strUrl];
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {

                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];

                }
            }];
        }
    }];
}

@end
